package com.facebook.app.client;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

import com.google.gwt.user.client.Cookies;

/**
 * Represents a Facebook cookie
 * 
 * @author Volker Jacht
 * 
 */
public class FacebookCookie {

	private String accessToken;
	private String expires;
	private String secret;
	private String sessionKey;
	private String sig;
	private String uid;
	private boolean isValid;
	
	
	/**
	 * 
	 * Pick out facebook cookie of all browser cookies, if it exists
	 * 
	 * @return Returns the content facebook cookie as String
	 */
	private String getFacebookCookie() {
		String fbCookie = null;
		List<String> allCookies = new ArrayList<String>(Cookies.getCookieNames());
		
		for(String cookie : allCookies) {
			if(cookie.contains("fb")) {
				fbCookie = cookie;
				break;
			}
		}

		if(fbCookie == null) {
			throw new NoSuchElementException("There is no facebook cookie");
		}
		
		return Cookies.getCookie(fbCookie);
	}
	
	/**
	 * 
	 * (Re)load facebook cookie and save its content
	 * 
	 */
	public void load() {
		try {
			save(getFacebookCookie());
			isValid = true;			
		} catch(NoSuchElementException e) {
			isValid = false;
		}
	}
	
	/**
	 * 
	 * Stores the content of the given cookie in this object.
	 * 
	 * @param String cookie, content of a facebook cookie as String
	 * 
	 */
	private void save(String cookie) {
		accessToken = cookie.substring(cookie.indexOf('=')+1,cookie.indexOf('&'));

		cookie = cookie.substring(cookie.indexOf('&') + 1);
		expires = cookie.substring(cookie.indexOf('=')+1,cookie.indexOf('&'));
		
		cookie = cookie.substring(cookie.indexOf('&') + 1);
		secret = cookie.substring(cookie.indexOf('=')+1,cookie.indexOf('&'));
		
		cookie = cookie.substring(cookie.indexOf('&') + 1);
		sessionKey = cookie.substring(cookie.indexOf('=')+1,cookie.indexOf('&'));
		
		cookie = cookie.substring(cookie.indexOf('&') + 1);
		sig = cookie.substring(cookie.indexOf('=')+1,cookie.indexOf('&'));
		
		cookie = cookie.substring(cookie.indexOf('&') + 1);
		uid = cookie.substring(cookie.indexOf('=')+1,cookie.indexOf('"'));
	}


	public String getAccessToken() {
		return accessToken;
	}

	
	public String getExpires() {
		return expires;
	}

	public String getSecret() {
		return secret;
	}
	
	public String getSessionKey() {
		return sessionKey;
	}


	public String getSig() {
		return sig;
	}

	
	public String getUid() {
		return uid;
	}
	
	
	public boolean isValid() {
		return isValid;
	}
}
